const WebsocketReadyState = {
    'CONNECTING': 0,//连接尚未建立
    'OPEN': 1,//连接已建立，可以进行通信
    'CLOSING': 2,//连接正在进行关闭
    'CLOSED': 3,//连接已经关闭或不能打开
}
class Rcon {
    constructor(ip = "localhost", port = "1000", password = '') {
        this.ip = ip
        this.port = port
        this.password = password
        this.socket = null
        this.queueContainer = {}//队列容器
        this.queueID = 2000//队列ID起始值
        this.events = {}//监听组
    }
    connect() {
        return new Promise((resolve, reject) => {
            if (!this.socket) {
                this.socket = new WebSocket(`ws://${this.ip}:${this.port}/${this.password}`)
                this.socket.onopen = () => {
                    if (this.isConnected()) {
                        resolve(this.socket)
                    }
                }
                this.socket.onerror = () => reject('连接错误')
                this.socket.onmessage = (evt) => {
                    let rconData = JSON.parse(evt.data)
                    if (rconData.Identifier > 2000) {
                        let cb = this.queueContainer[rconData.Identifier]
                        cb.callback(rconData)
                        //console.log(rconData)
                    }
                    delete this.queueContainer[rconData.Identifier]

                    if (this.events.hasOwnProperty(rconData.Type)) {
                        //console.error(rconData.Type,this.events)
                        this.events[rconData.Type].callback(rconData)
                    }
                }
            }
            else reject('已经连接过了')
        })
    }
    isConnected() {
        if (this.socket == null) {
            return false
        }
        return this.socket.readyState === WebsocketReadyState.OPEN
    }

    addQueue(message, callback) {
        this.queueID++
        this.queueContainer[this.queueID] = {
            callback
        }
        this.command(message, this.queueID)
    }
    send(message) {
        return new Promise((resolve, reject) => {
            this.addQueue(message, (data) => {
                resolve(data)
            })
        })
    }
    command(message, identifier = -1) {
        if (this.socket === null || !this.isConnected()) {
            return
        }
        let packet = {
            Identifier: identifier,
            Message: message,
            Name: 'WebRcon'
        }
        this.socket.send(JSON.stringify(packet))
    }
    disconnect() {
        if (this.socket) {
            this.socket.close()
            this.socket = null
        }
    }
    $on(event, callback) {
        this.events[event] ={callback} 
    }
}
export default Rcon